package com.example.stock.util;

/**
 * @Author tanlvxu
 * @Date 2024/12/18 17:53
 * @Description TODO
 */

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 判断今天是工作日/周末/节假日 工具类
 * //0 上班 1周末 2节假日
 */
public class HolidayUtil {


    static Map<String, List<String>> holiday =new HashMap<>();//假期
    static Map<String,List<String>> extraWorkDay =new HashMap<>();//调休日

    //判断是否为节假日
    /**
     *
     * @param time 日期参数 格式‘yyyy-MM-dd’，不传参则默认当前日期
     * @return
     */
    public static String isWorkingDay(String time) throws ParseException {
        Date parse = null;
        //为空则返回当前时间
        if (StringUtils.isNotBlank(time)){
            SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy-MM-dd");
            parse = getYearFormat.parse(time);
        }else {
            parse = new Date();
        }
        String newDate  = new SimpleDateFormat("yyyy").format(parse);

        //判断key是否有参数年份
        if(!holiday.containsKey(newDate)){
            String holiday = getYearHoliday(newDate);
            if ("No!".equals(holiday)){
                return "该年份未分配日期安排！";
            }
        }

        //得到日期是星期几
        Date date = DateUtil.formatStringToDate(time, false);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int weekday = DateUtil.getDayOfWeek(calendar);


        //是否节假日
        if(holiday.get(newDate).contains(time)){
            return "2";
        }else if(extraWorkDay.get(newDate).contains(time)){//是否为调休
            return "3";
        }else if(weekday == Calendar.SATURDAY || weekday == Calendar.FRIDAY){//是否为周末
            return "1";
        }else{
            return "0";
        }
    }

    /**
     *
     * @param date 日期参数 格式‘yyyy’，不传参则默认当前日期
     * @return
     */
    public static String getYearHoliday(String date) throws ParseException {

        //获取免费api地址
        String httpUrl="https://timor.tech/api/holiday/year/"+date;
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();

        try {
            URL url = new URL(httpUrl);
            URLConnection connection = url.openConnection();
            //connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            connection.setRequestProperty("User-Agent", "Mozilla/4.76");
            //使用Get方式请求数据
            //connection.setRequestMethod("GET");
            //connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            //字符串转json
            JSONObject json = JSONUtil.parseObj(sbf.toString());
            //根据holiday字段获取jsonObject内容
            JSONObject holiday = json.getJSONObject("holiday");
            if (holiday.size() == 0){
                return "No!";
            }
            List hoList = new ArrayList<>();
            List extraList = new ArrayList<>();
            for (Map.Entry<String, Object> entry : holiday.entrySet()) {
                String value = entry.getValue().toString();
                JSONObject jsonObject = JSONUtil.parseObj(value);
                String hoBool = jsonObject.getStr("holiday");
                String extra = jsonObject.getStr("date");
                //判断不是假期后调休的班
                if(hoBool.equals("true")){
                    hoList.add(extra);
                    HolidayUtil.holiday.put(date,hoList);
                }else {
                    extraList.add(extra);
                    HolidayUtil.extraWorkDay.put(date,extraList);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

